package com.yutian.example.demo.web.forum.controller;

import com.yutian.example.demo.common.exceptions.MyParamException;
import com.yutian.example.demo.common.vo.HttpResponse;
import com.yutian.example.demo.common.vo.PageData;
import com.yutian.example.demo.service.forum.IForumService;
import com.yutian.example.demo.service.forum.param.req.ForumListTopicReq;
import com.yutian.example.demo.service.forum.param.req.ForumPageTopicReq;
import com.yutian.example.demo.service.forum.param.rsp.ForumListTopicRsp;
import com.yutian.example.demo.service.forum.param.rsp.ForumPageTopicRsp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/forum")
public class ForumController {

    @Autowired
    private IForumService forumService;

    @GetMapping("topic/page")
    public HttpResponse pageTopic(ForumPageTopicReq req) {
        //显示主帖列表
        PageData<ForumPageTopicRsp> res = forumService.pageTopic(req);
        return HttpResponse.createSuc(res);
    }

    @GetMapping("topics")
    public HttpResponse listTopic(ForumListTopicReq req) {
        //显示主帖列表
        List<ForumListTopicRsp> res = forumService.listTopic(req);
        return HttpResponse.createSuc(res);
    }

    @GetMapping("topic/{topicId:[0-9]+}")
    public String showTopic(@PathVariable("topicId") Long topicId) {
        //显示单个主帖和它的跟贴
        return "topic";
    }

    @GetMapping("topic/{topicId:[0-9]+}/comment/{commentId:[0-9]+}")
    public String showComment(@PathVariable("topicId") int topicId, @PathVariable("commentId") int commentId) {
        //显示单个跟贴
        return "comment";
    }

    @PostMapping("topic")
    public String createTopic(@RequestBody String content){
        //创建一个主帖
        return "topic";
    }

    @PostMapping("topic/{topicId:[0-9]+}/comment")
    public String createComment(@PathVariable("topicId") int topicId, @RequestBody String content){
        //创建一个跟贴
        return "comment";
    }

    @PostMapping("upload")
    public HttpResponse upload(@RequestParam("file") MultipartFile file){
        String fileContent = null;
        try {
            fileContent = Streams.asString(file.getInputStream(), "UTF8");
        } catch (IOException e) {
            log.error("file.read.error: {}", file.getOriginalFilename(), e);
            throw new MyParamException("file.read.error");
        }
        return HttpResponse.createSuc(fileContent);
    }

    @PostMapping("uploads")
    public HttpResponse uploads(@RequestParam("files") MultipartFile[] files){
        return HttpResponse.createSuc(files.length);
    }
}